//
//  BELabelExtension.swift
//  BasicExtensions
//
//  Created by Fanxx on 2018/3/23.
//  Copyright © 2018年 fanxx. All rights reserved.
//

import UIKit

extension UILabel {
    ///获取在某个点上的文字索引，可用于点击事件根据对应的文字做不同的操作
    public func indexOfCharacter(at point: CGPoint) -> Int? {
        if let text = self.attributedText {
            let ps = NSMutableParagraphStyle()
            ps.lineBreakMode = self.lineBreakMode
            let at = NSMutableAttributedString(attributedString: text)
            let range = NSMakeRange(0, at.length)
            at.addAttributes([.paragraphStyle: ps], range: range)
            if let f = self.font {
                at.addAttributes([.font: f], range: range)
            }
            
            return at.indexOfCharacter(at: point, for: self.bounds.size, numberOfLines: self.numberOfLines)
        }
        return nil
    }
}
